<template>
  <div class="content-area">
    <!-- 筛选卡片 -->
    <div class="filter-card">
      <div class="filter-row">
        <div class="filter-item">
          <div class="filter-label">患者姓名</div>
          <el-input
            v-model="filters.patient_name"
            placeholder="请输入患者姓名"
            clearable
          />
        </div>
        <div class="filter-item">
          <div class="filter-label">身份证号</div>
          <el-input
            v-model="filters.id_number"
            placeholder="请输入身份证号"
            clearable
          />
        </div>
        <div class="filter-item">
          <div class="filter-label">医保卡号</div>
          <el-input
            v-model="filters.insurance_card_number"
            placeholder="请输入医保卡号"
            clearable
          />
        </div>
      </div>
      <div class="filter-row">
        <div class="filter-item">
          <div class="filter-label">挂号时间</div>
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            @change="handleDateRangeChange"
          />
        </div>
        <div class="filter-item">
          <div class="filter-label">就诊状态</div>
          <el-select
            v-model="filters.visit_status"
            placeholder="请选择状态"
            clearable
          >
            <el-option label="已挂号" value="registered" />
            <el-option label="就诊中" value="in_consultation" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </div>
      </div>
      <div class="action-buttons">
        <el-button @click="resetFilters">重置</el-button>
        <el-button type="primary" @click="searchVisits">查询</el-button>
      </div>
    </div>

    <!-- 预约挂号表格 -->
    <div class="appointment-table">
      <div class="table-header">
        <div class="table-title">预约挂号列表</div>
        <div class="table-tools">
          <el-button type="primary" @click="exportData">
            <el-icon><Document /></el-icon>
            导出数据
          </el-button>
          <el-button @click="refreshData">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </div>

      <el-table
        :data="visits"
        style="width: 100%"
        v-loading="loading"
        stripe
      >
        <el-table-column prop="visit_id" label="记录ID" width="80" />
        <el-table-column prop="appointment_id" label="挂号编号" width="150" />
        <el-table-column label="患者信息" min-width="220">
          <template #default="{ row }">
            <div class="patient-info">
              <div class="patient-avatar">
                <el-icon><User /></el-icon>
              </div>
              <div>
                <div class="patient-name">{{ row.patient_name }}</div>
                <div class="patient-meta">
                  {{ row.id_number }} · {{ row.phone_number || "无手机号" }}
                </div>
                <div class="patient-meta">
                  医保卡号: {{ row.insurance_card_number }}
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="挂号信息" width="200">
          <template #default="{ row }">
            <div>
              <div>类型: {{ getVisitTypeText(row.visit_type) }}</div>
              <div>费用: ¥{{ row.registration_fee }}</div>
              <div>时间: {{ formatDateTime(row.registration_time) }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="就诊安排" width="200">
          <template #default="{ row }">
            <div>
              <div>科室: {{ row.department_name }}</div>
              <div>医生: {{ row.doctor_name || "未分配" }}</div>
              <div v-if="row.visit_time">
                时间: {{ formatDateTime(row.visit_time) }}
              </div>
              <div v-else>时间: 未安排</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.visit_status)">
              {{ getStatusText(row.visit_status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons-cell">
              <el-button size="small" @click="viewDetails(row)">详情</el-button>
              <el-button
                size="small"
                type="danger"
                v-if="
                  row.visit_status === 'registered' ||
                  row.visit_status === 'in_consultation'
                "
                @click="cancelVisit(row)"
              >
                取消挂号
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 详情弹窗 -->
    <el-dialog v-model="detailDialogVisible" title="就诊记录详情" width="800px">
      <VisitDetail :visit-data="selectedVisit" :visit-id="selectedVisitId" v-if="selectedVisit" />
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { Document, Refresh, User } from '@element-plus/icons-vue';
import { useStore } from "vuex";
import VisitDetail from "@/components/doctor/VisitDetail.vue";
// 引入后端API接口数据
import { getDoctorReservationList } from "@/api/doctor.js";

const loading = ref(false);
const detailDialogVisible = ref(false);
const selectedVisit = ref(null);
const selectedVisitId = ref(null); // 新增：存储选中的就诊记录ID
const store = useStore();
const dateRange = ref([]);

const filters = reactive({
  patient_name: "",
  id_number: "",
  insurance_card_number: "",
  startDate: "",
  endDate: "",
  visit_status: "",
});

const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});

// 数据
const visits = ref([]);

// 状态映射
const statusMap = {
  registered: "已挂号",
  in_consultation: "就诊中",
  completed: "已完成",
  cancelled: "已取消",
};

const visitTypeMap = {
  outpatient: "门诊",
  emergency: "急诊",
  inpatient: "住院",
};

// 工具函数
const getStatusText = (status) => {
  return statusMap[status] || status;
};

const getVisitTypeText = (type) => {
  return visitTypeMap[type] || type;
};

const getStatusTagType = (status) => {
  const types = {
    registered: "primary",
    in_consultation: "warning",
    completed: "success",
    cancelled: "danger",
  };
  return types[status] || "";
};

const formatDateTime = (dateTime) => {
  if (!dateTime) return "";
  return new Date(dateTime).toLocaleString("zh-CN");
};

// 处理日期范围选择
const handleDateRangeChange = (dates) => {
  if (dates && dates.length === 2) {
    filters.startDate = dates[0];
    filters.endDate = dates[1];
  } else {
    filters.startDate = "";
    filters.endDate = "";
    dateRange.value = [];
  }
};

// 筛选和搜索
const resetFilters = () => {
  Object.keys(filters).forEach(key => {
    if (key !== 'startDate' && key !== 'endDate') {
      filters[key] = "";
    }
  });
  filters.startDate = "";
  filters.endDate = "";
  dateRange.value = [];
  pagination.currentPage = 1;
  loadVisits();
};

const searchVisits = () => {
  pagination.currentPage = 1;
  loadVisits();
};

// 数据加载
const loadVisits = async () => {
  loading.value = true;

  try {
    // 构造查询参数
    const queryParams = {
      doctor_id: store.state.user?.user_id,
      patient_name: filters.patient_name,
      id_number: filters.id_number,
      insurance_card_number: filters.insurance_card_number,
      visit_status: filters.visit_status,
      startDate: filters.startDate,
      endDate: filters.endDate,
      currentPage: pagination.currentPage,
      pageSize: pagination.pageSize,
    };
    
    // 调用API
    const response = await getDoctorReservationList(queryParams);
    console.log("获取的就诊记录数据:", response);
    if(response && response.code == 200){
      visits.value = response.data.data || [];
      pagination.total = response.data.total || 0;
    } else {
      ElMessage.error(response?.message || "加载就诊记录失败");
      visits.value = [];
      pagination.total = 0;
    }
    
  } catch (error) {
    ElMessage.error("加载就诊记录失败");
    console.error("加载就诊记录失败:", error);
    visits.value = [];
    pagination.total = 0;
  } finally {
    loading.value = false;
  }
};

// 分页处理
const handleSizeChange = (size) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  loadVisits();
};

const handleCurrentChange = (page) => {
  pagination.currentPage = page;
  loadVisits();
};

// 操作函数
const viewDetails = (row) => {
  selectedVisit.value = row;
  selectedVisitId.value = row.visit_id; // 设置选中的就诊记录ID
  detailDialogVisible.value = true;
};

const cancelVisit = async (row) => {
  try {
    // 这里需要调用取消挂号的API
    // await cancelReservationApi(row.visit_id);
    row.visit_status = "cancelled";
    ElMessage.warning(`已取消挂号：${row.patient_name}`);
  } catch (error) {
    ElMessage.error("取消挂号失败");
    console.error("取消挂号失败:", error);
  }
};

const exportData = () => {
  ElMessage.success("数据导出成功");
  // 实际项目中这里应该调用导出API
};

const refreshData = () => {
  loadVisits();
  ElMessage.success("数据已刷新");
};

onMounted(() => {
  loadVisits();
});
</script>

<style lang="scss" scoped>
/* 主内容区域样式 */
.content-area {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
  background-color: #f5f7fa;
  height: 0;
  min-height: 100%;
  overflow-y: auto;
}

/* 预约管理页面特定样式 */
.filter-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 24px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

.filter-row {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin-bottom: 16px;
}

.filter-item {
  display: flex;
  flex-direction: column;
  min-width: 200px;
  flex: 1;
}

.filter-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.action-buttons {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  margin-top: 16px;
}

.appointment-table {
  background: white;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.table-title {
  font-size: 18px;
  font-weight: 600;
}

.table-tools {
  display: flex;
  gap: 12px;
}

.action-buttons-cell {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.pagination {
  margin-top: 24px;
  display: flex;
  justify-content: flex-end;
}

.patient-info {
  display: flex;
  align-items: flex-start;
}

.patient-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  color: #1a75bc;
  flex-shrink: 0;
}

.patient-name {
  font-weight: 500;
  margin-bottom: 4px;
}

.patient-meta {
  font-size: 12px;
  color: #909399;
  line-height: 1.4;
}
</style>